#!/bin/env python
# -*- coding: utf-8 -*-

# get mirrors list

import sys, urllib
import os, gzip
import getopt
import re

SITE='http://mirrors.163.com'
FILE_OFFSET=len(SITE)+1
DIST_PREFIX='ubuntu/dists'
PLIST='Packages.gz'

def download_file(url, filename):
    pass

def get_package_url(dist, feature, branch='binary-amd64', plist=PLIST, dist_prefix=DIST_PREFIX, site=SITE):
    return '/'.join([site, dist_prefix, dist, feature, branch, plist])

def get_ubuntu_package_url(dist, branch='binary-amd64', site=SITE):
    ret = []
    for f in ['main', 'multiverse', 'restricted', 'universe']:
        ret.append(get_package_url(dist, f))
    return ret

def wget_file(f):
    print 'retrieving ', f
    filename = f[FILE_OFFSET:]
    fdir = os.path.dirname(filename)
    if not os.path.exists(fdir): os.makedirs(fdir)
    #print filename; exit(-1)
    urllib.urlretrieve(f, filename)
    return filename

def get_ubuntu_mirror_branch_list(site, dist, branch='binary-amd64'):
    ori_f = open('ori.'+dist+'.txt', 'w')

    for f in get_ubuntu_package_url(dist, branch):
        tempf = gzip.open(wget_file(f))
        file_content = tempf.read()
        tempf.close()

        msg = '################ '+f
        #print msg
        ori_f.writelines([msg, ''])
        ori_f.writelines(file_content)

    ori_f.close()        

def get_ubuntu_mirror_list(site, dist, branches=['binary-amd64']):
    for b in branches:
        get_ubuntu_mirror_branch_list(site, dist, b)

def get_ubuntu_dists_file(site, dist):
    ret = []
    ret.append('/'.join([site, DIST_PREFIX, dist, 'Release'          ]))
    ret.append('/'.join([site, DIST_PREFIX, dist, 'Release.gpg'      ]))
    ret.append('/'.join([site, DIST_PREFIX, dist, 'Contents-amd64.gz']))
    for f in ret:
        wget_file(f)

def usage():
    prog = sys.argv[0].split('\\')[-1]
    usagestr = 'Usage: ' + prog +' <dist> '+ u"""
    -l, --list        获取所有发行版列表， precise, trusty
""".encode('gbk')
    print usagestr

if __name__ == '__main__':
    # get all package list of a dist
    if len(sys.argv) == 1:
        usage()
        exit(-1)

    opts, args = getopt.getopt(
        sys.argv[1:],
        "hl",
        [
            "help", "list", 
        ]
    )

    for o, a in opts:
        if o in ('-h', '--help'):
            usage()
            sys.exit(2)

    dist = sys.argv[1]
    get_ubuntu_dists_file(SITE, dist)
    get_ubuntu_mirror_list(SITE, dist)
    os.system('bash get_info.sh '+dist)
